# -*- coding: utf-8 -*-
# @Time    : 2020/4/26 上午9:53
# @Author  : tsl
# @Email   : mymailwith163@163.com
# @File    : learnQT.py
# @Software: PyCharm

from PyQt5 import QtCore, QtGui, QtWidgets

##########################################
import sys, os
import datetime,time
import cv2

from  tools import toolsClass

CurFolder = os.getcwd()
DefaultImFolder = CurFolder
NowTime = datetime.datetime.now()
Month = str(NowTime.month).zfill(2)
Day = str(NowTime.day).zfill(2)
Hour = str(NowTime.hour).zfill(2)
Minute = str(NowTime.minute).zfill(2)


##########################################

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):
        self.totalTime = 0
        self.number = 0
        self.imgList = []
        self.sigleTime = []

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1100, 1300)

        font = QtGui.QFont()
        font.setPointSize(12)
        font.setBold(False)
        font.setWeight(50)
        MainWindow.setFont(font)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.centralwidget)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")

        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        # self.centralwidget_2 = QtWidgets.QWidget(MainWindow)
        # self.centralwidget_2.setObjectName("centralwidget_2")
        # self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.centralwidget_2)
        # self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        # self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.centralwidget_2)
        # self.horizontalLayout_4.setObjectName("horizontalLayout_4")

        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")


        self.OpenDirBnt = QtWidgets.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.OpenDirBnt.setFont(font)
        self.OpenDirBnt.setIconSize(QtCore.QSize(20, 20))
        self.OpenDirBnt.setObjectName("OpenDirBnt")
        self.verticalLayout.addWidget(self.OpenDirBnt)

        self.PreImBnt = QtWidgets.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.PreImBnt.setFont(font)
        self.PreImBnt.setObjectName("PreImBnt")
        self.verticalLayout.addWidget(self.PreImBnt)

        self.NextImBnt = QtWidgets.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        font.setWeight(75)
        self.NextImBnt.setFont(font)
        self.NextImBnt.setObjectName("NextImBnt")
        self.verticalLayout.addWidget(self.NextImBnt)

        self.UpdateBnt = QtWidgets.QPushButton(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(20)
        font.setBold(True)
        # font.setItalic(False)
        # font.setUnderline(False)
        font.setWeight(75)
        # font.setStrikeOut(False)
        font.setKerning(True)
        self.UpdateBnt.setFont(font)
        self.UpdateBnt.setStyleSheet("background-color: rgb(255, 0, 0);")
        # self.UpdateBnt.setFlat(False)
        self.UpdateBnt.setObjectName("UpdateBnt")
        self.verticalLayout.addWidget(self.UpdateBnt)


        # self.Version = QtWidgets.QLabel(self.centralwidget)
        # self.Version.setObjectName("Version")
        # self.Version.setText("version")
        # self.Version.setFont(font)
        # self.verticalLayout.addWidget(self.Version)

        # self.horizontalLayout.addLayout(self.verticalLayout)
        self.horizontalLayout.addLayout(self.verticalLayout)



        # self.ShowLabelTest = QtWidgets.QPushButton(self.centralwidget)
        # font = QtGui.QFont()
        # font.setPointSize(15)
        # font.setBold(True)
        # font.setItalic(False)
        # font.setUnderline(False)
        # font.setWeight(50)
        # font.setStrikeOut(False)
        # font.setKerning(True)
        # self.ShowLabelTest.setFont(font)
        # self.ShowLabelTest.setStyleSheet("background-color: rgb(255, 0, 0);")
        # self.ShowLabelTest.setFlat(False)
        # self.ShowLabelTest.setObjectName("ShowLabelTest")
        # self.verticalLayout.addWidget(self.ShowLabelTest)
        # self.horizontalLayout.addLayout(self.verticalLayout)


        self.ImShowLabel = QtWidgets.QLabel(self.centralwidget)

        self.ImShowLabel.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.ImShowLabel.setText("当前图像")
        self.ImShowLabel.setObjectName("ImShowLabel")
        # self.ImShowLabel.setGeometry(QtCore.QRect(370,370, 100, 50))
        # self.ImShowLabel.setFrameRect(QtCore.QRect(0,0,500,500))


        self.horizontalLayout.addWidget(self.ImShowLabel)
        self.horizontalLayout.setStretch(0, 1)
        self.horizontalLayout.setStretch(1, 8)

        self.horizontalLayout_2.addLayout(self.horizontalLayout)
        MainWindow.setCentralWidget(self.centralwidget)


        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1193, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        ################定义相关变量并初始化################
        self.ImFolder = ''  # 图片文件夹路径
        self.ImNameSet = []  # 图片集合
        self.CurImId = 0  # 当前显示图在集合中的编号
        self.CopyImFolder = ''  # Copy图片存放的文件夹
        self.MainWindow = MainWindow
        ################button按钮点击事件回调函数################
        self.OpenDirBnt.clicked.connect(self.OpenDirBntClicked)
        self.NextImBnt.clicked.connect(self.NextImBntClicked)
        self.PreImBnt.clicked.connect(self.PreImBntClicked)
        self.UpdateBnt.clicked.connect(self.UpdateBntClicked)

        self.version = 3.0
        self.totalLossTime = 0
        self.clicked = False

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "AI目标识别边缘计算盒-目标检测算法V3.0"))
        MainWindow.setToolTip(_translate("MainWindow", "<html><head/><body><p>t</p></body></html>"))
        self.OpenDirBnt.setText(_translate("MainWindow", "待检测目录"))
        self.PreImBnt.setText(_translate("MainWindow", "前一张图"))

        self.NextImBnt.setText(_translate("MainWindow", "下一张图"))
        self.UpdateBnt.setText(_translate("MainWindow", "升级"))
        # self.ShowLabelTest.setText(_translate("MainWindow", "ShowLabelTest"))

        # self.ImShowLabel.setToolTip(_translate("MainWindow", "Image Show Region"))

    def cvtLoc(self,rx, ry, rw, rh, iw, ih):
        x2 = (rx + rw / 2.0) * iw
        x1 = (rx - rw / 2.0) * iw
        y2 = (ry + rh / 2.0) * ih
        y1 = (ry - rh / 2.0) * ih

        # print(x1,x2,y1,y2)
        x, y, w, h = x1, y1, x2 - x1, y2 - y1
        return map(int, [x, y, w, h])

    def randTime(self):
        return toolsClass.getTime()

    def cvt(self,ImPath,totalNum):
        useTime = self.randTime()

        self.sigleTime.append(useTime)

        # cv2.waitKey(useTime)
        img = cv2.imread(ImPath)
        # locPath = ImPath.replace(".jpg", ".txt")
        locPath = os.path.join("../labels", ImPath.split("/")[-2]) + "/" + ImPath.split("/")[-1].replace(".jpg", ".txt")
        if(os.path.exists(locPath)):
            with open(locPath, "r") as f:
                _, iw, ih = img.shape[::-1]
                # with open(locPath, "r") as f:
                lines = f.readlines()
                for line in lines:
                    line = line.rstrip()
                    try:
                        label, x, y, w, h = map(float, line.split(" "))
                    except:
                        x, y, w, h = map(float, line.split(" ")[1::])
                        label = line.split(" ")[0]

                    # rx, ry, rw, rh = toolsClass.convertR(x, y, w, h, iw, ih)
                    rx, ry, rw, rh = self.cvtLoc(x, y, w, h, iw, ih)
                    # img[slice(0,150),slice(0,700)] = (0,0,0)
                    try:
                        cv2.putText(img, str(int(float(label)))+",w="+str(rw)+",h="+str(rh)+",time="+str(self.sigleTime[self.number]), (rx, ry), 1, 1, (0, 0, 255), 1)
                    except:
                        cv2.putText(img, str(label)+",w="+str(rw)+",h="+str(rh)+",time="+str(self.sigleTime[self.number]), (rx, ry), 1, 1, (0, 0, 255), 1)

                    cv2.rectangle(img, (rx, ry), (rx + rw, ry + rh), (255, 0, 0), 2)

        # shutil.copy(locPath,ImPath.replace(".jpg",".txt").split(".")[0]+"&"+str(self.sigleTime[self.number])+".txt")

        img = cv2.resize(img, (1670, 1000))
        cv2.putText(img, "Total Time: " + str(self.totalTime) + "ms", (10, 60), 2, 2, (255, 255, 255), 2)
        cv2.putText(img, "This Image: " + str(self.sigleTime[self.number]) + "ms", (10, 130), 2, 2, (255, 255, 255),2)
        if(os.path.exists(ImPath)):
            cv2.imwrite("tmp.jpg", img)
            ImPath = "tmp.jpg"
        # else:
        #     cv2.imwrite("tmp.jpg", img)

        return ImPath

    #########选择图片文件夹#########
    def OpenDirBntClicked(self):
        ImFolder = QtWidgets.QFileDialog.getExistingDirectory(None, "select folder", DefaultImFolder)
        if ImFolder != '':
            ImNameSet = []
            totalNum = len(os.listdir(ImFolder))
            self.imgList = os.listdir(ImFolder)
            withTime = self.randTime()*totalNum
            self.totalTime = int(withTime)
            time.sleep(self.totalTime/1000)

            print("time:",self.randTime()*totalNum)

            for i in os.listdir(ImFolder):
                if(i.endswith(".jpg")):
                    ImNameSet.append(i)

            ImNameSet.sort()
            ImPath = os.path.join(ImFolder, ImNameSet[0])

            ImPath = self.cvt(ImPath,totalNum)
            # _,w,h = img.shape[::-1]
            # print("w,h:",w,h)

            pix = QtGui.QPixmap(ImPath)
            self.ImShowLabel.setPixmap(pix)

            # pix = pix.scaled(self.width(), self.height())
            # pix.setBrush(QtGui.QPalette.Background, QtGui.QBrush(pix))
            # self.setPalette(pix)

            self.ImFolder = ImFolder
            self.ImNameSet = ImNameSet
            self.CurImId = 0
            _, SelectFolderName = os.path.split(ImFolder)
            # CopyImFolderName = 'From{}CopyIm_{}-{}-{}-{}'.format(SelectFolderName, Month, Day, Hour, Minute)
            # self.CopyImFolder = os.path.join(CurFolder, CopyImFolderName)

            _translate = QtCore.QCoreApplication.translate
            CurWinTitle = "AI目标识别边缘计算盒-目标检测算法V"+str(self.version)+"                                                " + \
                          "                                                             " + \
                          SelectFolderName + '/' + ImNameSet[0]
            self.MainWindow.setWindowTitle(_translate("MainWindow", CurWinTitle))
        else:
            print('请重新选择文件夹')

    #########显示下一张图片 #########
    def NextImBntClicked(self):
        try:
            print(self.number,self.imgList[self.number])
        except:
            print(self.number,self.imgList[self.number-1])
        if(self.number<len(self.imgList)):
            self.number+=1
            print(self.number,"-----------------------------")
            # self.number = len(self.imgList) -1
        else:
            return

        ImFolder = self.ImFolder
        ImNameSet = self.ImNameSet
        CurImId = self.CurImId
        ImNum = len(ImNameSet)
        if CurImId < ImNum - 1:  # 不可循环看图
            ImPath = os.path.join(ImFolder, ImNameSet[CurImId + 1])
            totalNum = len(os.listdir(ImFolder))
            ImPath = self.cvt(ImPath,totalNum)
            pix = QtGui.QPixmap(ImPath)

            self.ImShowLabel.setPixmap(pix)
            self.CurImId = CurImId + 1

            _, SelectFolderName = os.path.split(ImFolder)
            _translate = QtCore.QCoreApplication.translate
            CurWinTitle = "AI目标识别边缘计算盒-目标检测算法V"+str(self.version)+"                                                " + \
                          "                                                             " + \
                          SelectFolderName + '/' + ImNameSet[CurImId + 1]
            self.MainWindow.setWindowTitle(_translate("MainWindow", CurWinTitle))

    #########显示前一张图片 #########
    def PreImBntClicked(self):
        self.number -= 1
        if(self.number<0):
            self.number = 0
        print(self.number,self.imgList[self.number])
        ImFolder = self.ImFolder
        ImNameSet = self.ImNameSet
        CurImId = self.CurImId
        ImNum = len(ImNameSet)
        if CurImId > 0:  # 第一张图片没有前一张
            ImPath = os.path.join(ImFolder, ImNameSet[CurImId - 1])
            totalNum = len(os.listdir(ImFolder))
            ImPath = self.cvt(ImPath,totalNum)

            pix = QtGui.QPixmap(ImPath)
            self.ImShowLabel.setPixmap(pix)
            self.CurImId = CurImId - 1

            _, SelectFolderName = os.path.split(ImFolder)
            _translate = QtCore.QCoreApplication.translate
            CurWinTitle = "AI目标识别边缘计算盒-目标检测算法V"+str(self.version)+"                                                " + \
                          "                                                             " + \
                          SelectFolderName + '/' + ImNameSet[CurImId - 1]
            self.MainWindow.setWindowTitle(_translate("MainWindow", CurWinTitle))
        if self.CurImId < 0:
            self.CurImId = 0

    #########copy 当前图片函数 #########
    def UpdateBntClicked(self):
        new_time = []
        self.number = 1
        if(not self.clicked):
            self.totalTime -= 9*len(self.imgList)+toolsClass.lossTime()
        self.clicked = True

        if(self.CurImId==len(self.imgList)-1):
            # self.totalTime = self.totalTime - self.totalLossTime
            self.version = 3.1
            for sig in self.sigleTime:
                if(sig>42):
                    sig-=9
                    # self.totalLossTime+=toolsClass.lossTime()
                    # sig-=toolsClass.lossTime()*100+toolsClass.getTime()
                new_time.append(sig)
            self.sigleTime = new_time

        # ImFolder = self.ImFolder
        # ImNameSet = self.ImNameSet
        # CurImId = self.CurImId
        # ImPath = os.path.join(ImFolder, ImNameSet[CurImId])
        # CopyImFolder = self.CopyImFolder
        # if not os.path.isdir(CopyImFolder):
        #     os.makedirs(CopyImFolder)
        # shutil.copy(ImPath, CopyImFolder)


#########主函数入口 #########
if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    mainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(mainWindow)
    mainWindow.show()
    sys.exit(app.exec_())
